package com.cdu.controller;

import com.cdu.commons.*;
import com.cdu.pojo.dto.FavoriteDTO;
import com.cdu.pojo.dto.ProductPageQueryDTO;
import com.cdu.pojo.dto.TokenUser;
import com.cdu.service.ProductService;
import com.cdu.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
@RequestMapping("/api/product")
@RequiredArgsConstructor
public class ProductController {

    private final ProductService productService;

    @PostMapping("/find")
    public R<PageR> producePageQuery(ProductPageQueryDTO productPageQueryDTO){
        log.info("分页查询商品：{}", productPageQueryDTO);
        PageR pageR= productService.page(productPageQueryDTO);
        return new  R<PageR>().ok("查询成功",pageR);
    }

    @PostMapping("/favorite")
    public R<Void> favorite(FavoriteDTO favoriteDTO, HttpServletRequest httpServletRequest){
        log.info("收藏商品：{}",favoriteDTO);
        String token=httpServletRequest.getHeader(MallConstants.TOKEN_SIGN);
        if (token == null){
            throw new ServiceException("请先登录", ServiceCode.NO_LOGIN_CODE);
        }
        TokenUser tokenUser= JwtUtils.getTokenUser(token);
        favoriteDTO.setUserId(tokenUser.getId());
        favoriteDTO.setCreatedUser(tokenUser.getUsername());
        productService.favorite(favoriteDTO);
        return R.ok("收藏成功");
    }
}
